'use strict'

let watermark = {}

let setWatermark = (str) => {
  let id = '1.23452384164.123412415'

  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id))
  }

  let can = document.createElement('canvas')
  // 宽高决定水印的密度
  can.width = 300
  can.height = 300

  let cans = can.getContext('2d')
  // 水印角度
  cans.rotate(-25 * Math.PI / 180)
  cans.font = '14px Vedana'
  cans.fillStyle = 'rgba(221, 221, 221, 0.3)'
  cans.textAlign = 'left'
  cans.textBaseline = 'Middle'
  cans.fillText(str, can.width / 16, can.height / 2)
  cans.fillText(str, can.width / 8, can.height / 1)
  let div = document.createElement('div')
  div.id = id
  // 除了指示该元素不是鼠标事件的目标之外，值none表示鼠标事件“穿透”该元素并且指定该元素“下面”的任何东西。
  div.style.pointerEvents = 'none'
  div.style.top = '130px'
  div.style.left = '240px'
  div.style.position = 'fixed'
  div.style.zIndex = '10000000'// 层级加到足够高时，弹窗也可有水印
  div.style.width = document.documentElement.clientWidth - 10 + 'px'
  div.style.height = document.documentElement.clientHeight - 100 + 'px'
  div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
  document.body.appendChild(div)
  return id
}

// 该方法只允许调用一次
watermark.set = (str) => {
  let id = setWatermark(str)
  setInterval(() => {
    if (document.getElementById(id) === null) {
      id = setWatermark(str)
    }
  }, 500)
  window.onresize = () => {
    setWatermark(str)
  }
}

export default watermark
